
//
// 110624 - AH - Created.
// 110626 - AH - In encode(String) and writeEncoded(PrintWriter, String) trims 
//               encoded strings. 
//

package org.soekrat.engine.io;

import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * <p>
 *   Utility methods for Soekrat I/O.
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC) 
 */
public final class IOUtil 
{
  private IOUtil(){} // Utility pattern dictates private constructor.
  
  /**
   * <p>
   *   Encode data that needs encoding for Soekrat storage.
   * </p>
   * @param data Data needing encoding.
   * @return Encoded representation.
   */
  public static String encode(String data)
  {
    if (data==null) return null;
    
    data=data.trim();
    if (data.length()==0) return null;
    
    try
    {
      String retVal=URLEncoder.encode(data, "UTF-8");
      return retVal.trim();
    }
    catch (UnsupportedEncodingException uex)
    { 
      uex.printStackTrace(); // This never happens.
      throw new Error();
    }
  }
  
  /**
   * <p>
   *   Encode data that needs to be written encoded for Soekrat storage.
   * </p>
   * @param pw   {@link PrintWriter} Stream to write to.
   * @param data Data to encode.
   */
  public static final void writeEncoded(PrintWriter pw, String data)
  {
    if (data==null) return;
    
    data=data.trim();
    if (data.length()==0) return;
    
    try
    {
      String encoded=URLEncoder.encode(data, "UTF-8");
      encoded=encoded.trim();
      pw.print(encoded);
    }
    catch (UnsupportedEncodingException uex)
    { 
      uex.printStackTrace(); // This never happens.
      throw new Error();
    }
  }
  
  /**
   * <p>
   *   Decode data been encoded using
   *   {@link #encode(String)} or
   *   {@link #writeEncoded(PrintWriter, String)}.
   * </p>
   * @param data Data to decode.
   * @return Decoded data.
   */
  public static String decode(String data)
  {
    if (data==null) return null;
    try
    {
      String retVal=URLDecoder.decode(data, "UTF-8");
      retVal=(retVal==null) ? "" : retVal.trim();
      return retVal;
    }
    catch (UnsupportedEncodingException uex)
    { 
      uex.printStackTrace(); // This never happens.
      throw new Error();
    }
  }
  
}
